package com.lovesher.payment.service.resposity.dao.impl;

import javax.annotation.Resource;

import com.lovesher.payment.service.dubbo.CenterService;
import com.lovesher.payment.service.dubbo.ShopService;
import com.lovesher.payment.service.resposity.dao.PaymentDao;
import com.lovesher.payment.service.resposity.dao.PaymentSerialDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lovesher.payment.common.enums.PayStatus;
import com.lovesher.payment.common.enums.PayType;
import com.lovesher.payment.common.resposity.bean.PaymentSerial;
import com.lovesher.payment.service.dubbo.CenterService;
import com.lovesher.payment.service.dubbo.ShopService;
import com.lovesher.payment.service.resposity.dao.PaymentDao;
import com.lovesher.payment.service.resposity.dao.PaymentSerialDao;

@Service("paymentDao")
public class PaymentDaoImpl implements PaymentDao {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Resource
	private PaymentSerialDao paymentSerialDao;
	
	@Resource
	private CenterService centerService;
	
	@Resource
	private ShopService shopService;
	

	@Override
	@Transactional
	public void handle(PaymentSerial paymentSerial, String returnText, PayStatus payStatus) {
		
		/**新增支付成功流水**/
		PaymentSerial npaymentSerial = new PaymentSerial();
		npaymentSerial.setId(paymentSerial.getId());
		if(payStatus == PayStatus.SUCCESS){
			/**充值成功*/
			try{
				if(paymentSerial.getType() == PayType.RECHARGE.getValue()){
					//更新订单状态
					logger.info("进入center处理业务开始");
					centerService.getRechargeService().callback(paymentSerial.getTradeNo(), returnText, Boolean.TRUE);
					logger.info("进入center处理业务结束");
				}
				if(paymentSerial.getType() == PayType.SHOPPING.getValue()){
					//更新订单状态
					logger.info("进入shop处理业务开始");
					shopService.getShopRechargeService().callback(paymentSerial.getOrderSn(), returnText, Boolean.TRUE);
					logger.info("进入shop处理业务结束");
				}
				if(paymentSerial.getType() == PayType.REFUND.getValue()){
					//更新订单状态
					logger.info("退款处理业务开始");
					logger.info("退款处理业务结束");
				}
				npaymentSerial.setStatus(PayStatus.SUCCESS.getValue());
				logger.info(new StringBuffer("订单号:").append(paymentSerial.getOrderSn()).append(" 处理成功!").toString());
			}catch (RuntimeException e) {
				logger.error(new StringBuffer("订单号:").append(paymentSerial.getOrderSn()).append(" 处理失败!").append(e.getMessage()).toString(),e);
				npaymentSerial.setStatus(PayStatus.FAILURE.getValue());
			}
		}else{
			/**充值失败*/
			centerService.getRechargeService().callback(paymentSerial.getOrderSn(), returnText, Boolean.FALSE);
			npaymentSerial.setStatus(PayStatus.FAILURE.getValue());
		}
		this.paymentSerialDao.update(npaymentSerial);
		
	}
	
}
